<template>
  <div class="wrap-container">
    <div class="card_left">
      <el-card>
        <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
          <div class="manage_tit">
            <div class="line"></div>
            <p>{{ activeName == '0' ? '新建优惠券' : '新建卡券' }}</p>
          </div>
          <!-- <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="新建优惠券" key="0">
            </el-tab-pane>
            <el-tab-pane label="新建卡券" key="1">
            </el-tab-pane>
          </el-tabs> -->
          <div class="card_coupon" v-if="activeName == '0'">
            <div
              v-for="(dict, index) in dict?.type?.coupon_type"
              :key="index"
              @click="handleTypeClick(dict)"
            >
              <div :class="['type_coupon', { active: form.type == dict.value }]">
                <div class="type_title">{{ dict.label }}</div>
                <div class="type_content">{{ dict.raw.remark }}</div>
              </div>
            </div>
            <div>
              <div class="type_coupon">
                <div class="type_title">更多优惠券</div>
                <div class="type_content">敬请期待</div>
              </div>
            </div>
          </div>
          <div class="card_coupon" v-else-if="activeName == '1'">
            <div
              v-for="(dict, index) in dict?.type?.pass_type"
              :key="index"
              @click="handleTypeClick(dict)"
            >
              <div :class="['type_coupon', { active: form.type === dict.value }]">
                <div class="type_title">{{ dict.label }}</div>
                <div class="type_content">{{ dict.raw.remark }}</div>
              </div>
            </div>
            <div>
              <div class="type_coupon">
                <div class="type_title">更多卡券</div>
                <div class="type_content">敬请期待</div>
              </div>
            </div>
          </div>
          <div class="divider"></div>

          <span class="form-title">*基本信息</span>
          <el-form-item label="优惠券名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请填写优惠券名称"
              maxlength="40"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="渠道备注">
            <el-input
              v-model="form.mname"
              placeholder="请填写渠道备注"
              maxlength="20"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="场馆备注">
            <el-input
              v-model="form.bname"
              placeholder="请填写场馆备注"
              maxlength="20"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="发布渠道" prop="sourceType">
            <el-select
              style="width: 100%"
              filterable
              clearable
              v-model="form.sourceType"
              placeholder="请选择发布渠道"
            >
              <el-option
                v-for="dict in dict?.type?.platform_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="优惠券面值"
            prop="faceValue"
            v-if="activeName == '0' && form.type != '2'"
          >
            <div class="div_group">
              <!-- <el-radio label="1"> -->
              <el-input
                style="width: 125px"
                v-model="form.faceValue"
                type="number"
                placeholder="¥ 0.00"
                clearable
              />
              <span class="ml-15px">元</span>
              <!-- </el-radio> -->
            </div>
          </el-form-item>

          <el-form-item
            label="使用条件"
            prop="thresholdAmount"
            v-if="activeName == '0' && form.type == '3'"
          >
            <!-- <el-radio-group> -->
            <!--                  <el-radio label="1">无门槛</el-radio>-->
            <!-- <el-radio label="2"> -->
            <span class="mr-15px">订单满</span>
            <el-input
              style="width: 125px"
              v-model="form.thresholdAmount"
              type="number"
              placeholder="最低金额"
              clearable
            />
            <span class="ml-15px">元</span>
            <!-- </el-radio>
            </el-radio-group> -->
          </el-form-item>
          <span class="form-title" v-if="activeName == '1'">*卡券设置</span>

          <el-form-item
            label="卡券类型"
            prop="card.cardType"
            class="limit_item"
            v-if="activeName == '1' && false"
          >
            <el-radio-group v-model="form.card.cardType">
              <el-radio label="1">次卡</el-radio>
              <el-radio label="2">周卡</el-radio>
              <el-radio label="3">月卡</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="使用次数" prop="totalCount" v-if="activeName == '1'">
            <el-input
              v-model="form.totalCount"
              type="number"
              placeholder="请填写使用次数"
              clearable
            />
          </el-form-item>
          <el-form-item label="每天限次" prop="dailyLimit" v-if="activeName == '1'">
            <el-input
              v-model="form.dailyLimit"
              type="number"
              placeholder="请填写每天限次"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="抵扣时长"
            prop="freeHours"
            v-if="activeName == '1' || (activeName == '0' && form.type == '2')"
          >
            <el-input v-model="form.freeHours" type="number" placeholder="请填写抵扣时长" clearable>
              <template #append>小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="其他说明">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 10 }"
              placeholder="请输入优惠券相关说明（非必填项）"
              v-model="form.remark"
              clearable
            >
            </el-input>
          </el-form-item>
          <div class="footer">
            <el-button type="primary" @click="handleSubmit" class="approval_btn"
              >提交审核</el-button
            >
            <el-button type="primary" @click="saveForm" class="save_btn">保存</el-button>
            <el-button @click="handleClose">取消</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
    <approval-dialog ref="approvalDialogRef" @sure="goJumpPage"></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { addCoupon, addPass } from '@/api/coupon/coupon'
import { getRedis, addRedis } from '@/api/common/sysCommon'
import { debounce } from '@/utils'
import WarnDialog from '../../components/common/warnDialog.vue'
import approvalDialog from '@/components/Approval/approvalDialog.vue'

// 字典数据
const { dict } = useDict({
  dicts: ['site_type', 'coupon_type', 'pass_type', 'platform_type', 'sys_normal_disable'],
})

// 定义响应式数据
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance | null>(null)
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)

const activeName = ref('') //0表示优惠券，1表示卡券

const form = reactive({
  type: '3', //券类型
  name: null as string | null, //优惠券名称
  mname: null as string | null, //m端名
  bname: null as string | null, //b端名
  sourceType: null as string | null, //发布渠道
  faceValue: null as number | null, //优惠券面额
  thresholdAmount: null as number | null, //满减总额度
  freeHours: 1, //抵扣时长
  dailyLimit: 1, //每日限用次数
  totalCount: 1, //卡券总可用次数
  remark: null as string | null, //其他说明
  card: {
    cardType: '1', //卡券类型
    cardUseNum: 1, //卡券使用次数
    cardUseNumDay: 1, // 卡券每天使用次数
    offsetHours: 1, // 抵扣时长
  },
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请填写优惠券名称', trigger: 'change' }],
  sourceType: [{ required: true, message: '请选择发布渠道', trigger: 'change' }],
  thresholdAmount: [{ required: true, message: '请选择使用条件', trigger: 'change' }],
  faceValue: [{ required: true, message: '请填写优惠券面值', trigger: 'change' }],
  freeHours: [{ required: true, message: '请填写抵扣时长', trigger: 'change' }],
  dailyLimit: [{ required: true, message: '请填写每日限次', trigger: 'change' }],
  totalCount: [{ required: true, message: '请填写卡券总可用次数', trigger: 'change' }],
})

const processedInput = computed({
  get() {
    return form.name // 返回原始输入值显示在 input 中
  },
  set(value) {
    // @ts-ignore
    const valid = /^[1-9]\d*$/.test(value) // 验证是否为正整数
    if (valid) {
      form.name = value // 如果是正整数，更新原始输入值
    } else {
      // @ts-ignore
      form.name = form.name?.replace(/\D/g, '') // 否则移除非数字字符
    }
  },
})

onMounted(() => {
  if (route.query.type) {
    activeName.value = route.query.type as string
  }
  if (route.query.form) {
    // 复制
    Object.assign(form, JSON.parse(route.query.form as string))
  } else {
    loadRedis()
  }
})

// 监听优惠券类型字典,默认选中第一个
watch(
  () => dict.value.type.coupon_type,
  (val) => {
    if (!route.query.form && activeName.value == '0' && val.length > 0) {
      form.type = dict.value.type.coupon_type[0].value
    }
  },
)

watch(
  () => dict.value.type.pass_type,
  (val) => {
    if (!route.query.form && activeName.value == '1' && val.length > 0) {
      form.type = dict.value.type.pass_type[0].value
    }
  },
)

// 加载redis缓存
const loadRedis = () => {
  let key = ''
  if (activeName.value == '0') {
    key = 'couponDraft'
  } else {
    key = 'passDraft'
  }
  const localStorageKey = localStorage.getItem(key)
  if (localStorageKey) {
    getRedis({ key: localStorageKey }).then((res: any) => {
      ElMessageBox.confirm(`有历史草稿数据，是否要使用？`)
        .then(() => {
          Object.assign(form, JSON.parse(res.msg))
        })
        .catch(() => {})
    })
  }
}

// 类型选中变色
const handleTypeClick = (dict: any) => {
  // 清除格式校验
  formRef.value?.clearValidate()
  form.type = dict.value
}

// 提交
const handleSubmit = debounce(
  () => {
    try {
      if (!formRef.value) return
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (activeName.value == '0') {
            // 新建优惠券
            await addCoupon(form).then((res: any) => {
              if (approvalDialogRef.value) {
                approvalDialogRef.value.approvalVisible = true
              }
            })
          } else {
            // 新建卡券
            await addPass(form).then((res: any) => {
              if (approvalDialogRef.value) {
                approvalDialogRef.value.approvalVisible = true
              }
            })
          }
        }
      })
    } catch (e) {
      ElMessage.error((e as Error) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 保存
const saveForm = () => {
  ElMessageBox.confirm(`是否保存为草稿？`)
    .then(() => {
      const params = {
        value: form,
        // expire: 1140
      }
      return addRedis(params).then((res: any) => {
        if (activeName.value == '0') {
          localStorage.setItem('couponDraft', res.msg)
        } else {
          localStorage.setItem('passDraft', res.msg)
        }
      })
    })
    .then(() => {
      ElMessage.success('操作成功')
    })
    .catch(() => {})
}

// 取消
const handleClose = () => {
  router.go(-1)
}

// 提交审核之后跳转到审核中心
const goJumpPage = () => {
  if (activeName.value == '0') {
    router.push({ path: '/approval/couApproval' })
  } else {
    router.push({ path: '/approval/passApproval' })
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-card) {
  height: calc(100vh - 80px);
  overflow-y: auto;
}

.card_left {
  .card_coupon {
    display: flex;
    margin-top: 15px;
  }

  .type_coupon {
    cursor: pointer;
    width: 206px;
    height: 118px;
    padding: 20px;
    border-radius: 9px;
    background-color: rgba(241, 247, 255, 1);
    text-align: center;
    margin: 0 15px 0 0;

    .type_title {
      font-size: 16px;
      font-weight: 500;
      color: rgba(56, 56, 56, 1);
      margin: 0 0 20px 0;
    }

    .type_content {
      font-size: 14px;
      font-weight: 400;
      color: rgba(128, 128, 128, 1);
    }

    &.active {
      background-color: rgba(9, 136, 251, 1);

      .type_title {
        color: rgba(255, 255, 255, 1);
      }

      .type_content {
        color: rgba(255, 255, 255, 1);
      }
    }
  }

  .divider {
    margin: 15px 0;
    opacity: 1;
    height: 1px;
    background: #e5e5e5;
  }

  .form-title {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: rgba(42, 130, 228, 1);
    margin-bottom: 15px;
  }

  .div_group {
    margin: 0 0 15px 0;
  }

  .divider_text {
    font-size: 14px;
    font-weight: 400;
    color: rgba(42, 130, 228, 1);
  }

  .button_group {
    font-size: 14px;
    font-weight: 400;
  }
}

.card_right {
  margin: 0 0 0 20px;
}

.footer {
  text-align: center;
  margin-top: 50px;
  .el-button {
    width: 70px;
    height: 35px;
    border-radius: 8px;
    & + .el-button {
      margin-left: 14px;
    }
  }
  .approval_btn {
    width: 95px;
  }
  .save_btn {
    background: rgba(255, 141, 26, 1);
    border-color: rgba(255, 141, 26, 1);
  }
}
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 15px;
    &.limit_item {
      margin-bottom: 0;
      .div_group {
        margin-bottom: 8px;
      }
    }
    .radio_item {
      margin-bottom: 0;
    }
  }
  .el-form-item__label {
    padding-right: 19px;
  }
  .el-icon--right {
    margin-left: 0;
  }
}
:deep(.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner) {
  outline: none;
  box-shadow: none;
}